#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    resize(1280, 720);
    tcpclient = new QTcpSocket(this);
    lb_device_list = new QLabel(this);

    lb_device_list->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    lb_device_list->setStyleSheet("QLabel { background-color: white; }");
    lb_device_list->setScaledContents(true);
    lb_device_list->show();


    /* 1.创建udp通信套接字 */
    udpclient = new QUdpSocket(this);
    /* 2.udp通信接收 */
    QObject::connect(udpclient,&QUdpSocket::readyRead,this,&Widget::udpReceive);

    pB_udp_broadcast = new QPushButton("udp广播搜索设备",this);
    pB_udp_broadcast->setGeometry(950, 170, 100, 30);
    connect(pB_udp_broadcast,SIGNAL(clicked()),this,SLOT(udpBroadcast()));

    pB_tcp_open = new QPushButton("tcp连接",this);
    pB_tcp_open->setGeometry(1050, 170, 100, 30);
    connect(pB_tcp_open,SIGNAL(clicked()),this,SLOT(tcpConnect()));


    pB_tcp_close = new QPushButton("tcp连接断开",this);
    pB_tcp_close->setGeometry(1150, 170, 100, 30);
    connect(pB_tcp_close,SIGNAL(clicked()),this,SLOT(tcpDisconnect()));

    tcpclient = new QTcpSocket(this);

    connect(tcpclient,&QTcpSocket::connected,[=](){
//        ui->textEditRead->setText("服务器连接成功！");
    });

    connect(tcpclient,&QTcpSocket::readyRead,[=](){
//        //获取通信套接字的内容
//        QString str=tcpsocket->readAll();
//        //在显示编辑区域显示
//        ui->textEditRead->append("服务器端："+str);//不用settext 这样会覆盖之前的消息
    });





    up_motor_speed = new QLabel(this);
    down_motor_speed = new QLabel(this);
    pitch_angle = new QLabel(this);
    yaw_angle = new QLabel(this);
    repetition = new QLabel(this);
    frequency = new QLabel(this);
    le_up_motor_speed = new QLineEdit("0",this);
    le_down_motor_speed = new QLineEdit("0",this);
    le_pitch_angle = new QLineEdit("0.0",this);
    le_yaw_angle = new QLineEdit("0.0",this);
    le_repetition = new QLineEdit("0",this);
    le_frequency = new QLineEdit("0.0",this);


    up_motor_speed->setText("上轮速度");
    down_motor_speed->setText("下轮速度");
    pitch_angle->setText("俯仰角度");
    yaw_angle->setText("左右角度");
    repetition->setText("次数");
    frequency->setText("频率");

    lb_device_list->setGeometry(950, 200, 300, 450);
    up_motor_speed->setGeometry(90,200,100,30);
    le_up_motor_speed->setGeometry(90,235,100,30);

    down_motor_speed->setGeometry(240,200,100,30);
    le_down_motor_speed->setGeometry(240,235,100,30);

    pitch_angle->setGeometry(390,200,100,30);
    le_pitch_angle->setGeometry(390,235,100,30);
//    le_pitch_angle->setText("0");

    yaw_angle->setGeometry(540,200,100,30);
    le_yaw_angle->setGeometry(540,235,100,30);

    repetition->setGeometry(690,200,100,30);
    le_repetition->setGeometry(690,235,100,30);

    frequency->setGeometry(840,200,100,30);
    le_frequency->setGeometry(840,235,100,30);

    device_select = new QComboBox(this);
    device_select->setGeometry(0,235,60,20);

//    QComboBox *serve_kind_select = nullptr;
//    QComboBox *serve_degree_select = nullptr;
//    QComboBox *serve_sort_select = nullptr;
    serve_kind_select = new QComboBox(this);
    serve_kind_select->setGeometry(0,690,100,30);
    serve_kind_select->addItem("时间");
    serve_kind_select->addItem("组数");
    serve_kind_select->addItem("次数");
    serve_kind_select->addItem("无限");

    serve_sort_select = new QComboBox(this);
    serve_sort_select->addItem("顺序模式");
    serve_sort_select->addItem("随机模式");
    serve_sort_select->setGeometry(200,690,100,30);
    device_select->addItem("设备1");
    device_select->addItem("设备2");

    le_serve_degree = new QLineEdit(this);
    le_serve_degree->setGeometry(100,690,100,30);

    le_group_gap = new QLineEdit(this);
    le_group_gap->setGeometry(375,690,100,30);
    lb_group_gap = new QLabel(this);
    lb_group_gap->setText("组间间隔(s)：");
    lb_group_gap->setGeometry(300,690,70,30);

    le_countdown = new QLineEdit(this);

    lb_countdown = new QLabel(this);
    lb_countdown->setText("倒计时(s)：");
    lb_countdown->setGeometry(490,690,60,30);
    le_countdown->setGeometry(550,690,100,30);
    pB_skip_countdown = new QPushButton("跳过倒计时",this);
    pB_skip_countdown->setGeometry(650,690,100,30);

    pB_start_serve = new QPushButton("开始发球",this);
    pB_start_serve->setGeometry(750, 690, 100, 30);
    connect(pB_start_serve,SIGNAL(clicked()),this,SLOT(start_serve()));

    my_course_data = new COURSE_DATA();
    memset(my_course_data,0,sizeof(my_course_data));


    time_udp_broadcast = new QTimer();
    time_udp_broadcast->setInterval(1000);
    time_udp_broadcast->start();
    connect(time_udp_broadcast,SIGNAL(timeout()),this,SLOT(time_udp_broadcast_out()));



    log = new QTextEdit(this);
    log->setGeometry(950,0,300,170);

    current_time = new QDateTime();
//    *current_time = QDateTime::currentDateTime();

    device1 = new MY_DEVICE();
    device2 = new MY_DEVICE();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::udpReceive()
{

    qDebug() << "收到udp数据";
    QHostAddress addr; //用于获取发送者的 IP 和端口
    quint16 port;
    //数据缓冲区
    QByteArray arr;
    while(udpclient->hasPendingDatagrams())
    {
        //调整缓冲区的大小和收到的数据大小一致
        arr.resize(udpclient->bytesAvailable());

        //接收数据
        udpclient->readDatagram(arr.data(),arr.size(),&addr,&port);
        //显示
        QString str = QString(arr);
        lb_device_list->setText(str);

        handleUdpData(arr);
    }
}

void Widget::udpBroadcast()
{
    qDebug() << "udp广播测试";
    char udp_broadcast_data_package[9] = {(char)0x41, (char)0x14, (char)0x05, (char)0x00, (char)0x07,(char)0x00,(char)0x00,(char)0x59,(char)0xc1};
    QByteArray udp_broadcast_data;
    udp_broadcast_data.resize(9);
    memcpy(udp_broadcast_data.data(),&udp_broadcast_data_package[0],sizeof(udp_broadcast_data_package));
    udpclient->writeDatagram(udp_broadcast_data,QHostAddress::Broadcast,60001);
}

void Widget::handleUdpData(QByteArray recdata)
{
    if(recdata.at(0) == (char)0x45 && recdata.at(1) == char(0x54))
    {
        memcpy(device1->ip,recdata.data()+8,sizeof(device1->ip));
        memcpy(device1->dynamic_code,recdata.data()+22+8,sizeof(device1->dynamic_code));
        memcpy(device1->sn,recdata.data()+18,sizeof(device1->sn));
//        qDebug() << "ip" << device1->ip;
        QByteArray ip;
        ip.resize(4);
        memcpy(ip.data(),device1->ip,4);
        qDebug() << ip.toHex();
        qDebug() << "code" << device1->dynamic_code;
        lb_device_list->setText("设备1   ip地址:");

        uint8_t bb[4] = {0};
        memcpy(bb,ip.data(),4);
//        QString str1="0";QString str2="0";
//        QString str3="0";QString str4="0";
//        str1 = QString::number(ip.at(0),10);
//        str2 =
//        str3 = QString(ip.at(2));
//        str4 = QString(ip.at(3));

//        qDebug() << bb[0];
        outputIp(bb);

        QByteArray sn;
        sn.resize(12);
        memcpy(sn.data(),device1->sn,12);
        qDebug() << sn;


    }
}


void Widget::tcpConnect()
{
    uint8_t ipaddressU8[4];
    quint32 ipaddressU32 = 0;

    memcpy(ipaddressU8,device1->ip,4);
    ipaddressU32 = ipaddressU8[0]<<24 |ipaddressU8[1]<<16|ipaddressU8[2]<<8|ipaddressU8[3];
    QHostAddress ipaddress = QHostAddress(ipaddressU32);


    tcpclient->connectToHost(ipaddress,8080);

    char privatekey[32] = {0};


    if (tcpclient->waitForConnected(1000))  // 连接成功则进入if{}
    {
        log->append("设备1 tcp连接成功");
        int retvalue = 0;
        retvalue = dynaPrivateKeyGet(device1->sn, device1->ip, privatekey);


    }
//        log->append("设备1 tcp连接成功");
}

void Widget::tcpDisconnect()
{
    tcpclient->disconnectFromHost();
    if (tcpclient->state() == QAbstractSocket::UnconnectedState || tcpclient->waitForDisconnected(1000))  //已断开连接则进入if{}
    {
        log->append("设备1 断开成功");
    }
}

void Widget::tcpSend(QByteArray senddata)
{
    if(tcpclient == nullptr)
    {
        lb_device_list->setText("发送失败,tcp连接异常");
        return;
    }
    tcpclient->write(senddata.data());
}

void Widget::tcpReceive()
{

}

void Widget::start_serve()
{

//    typedef struct Course_Data {
//        quint8 serve_kind;
//        quint16 serve_degree;
//        quint8 serve_sort;
//        float between_group_time;
//        quint8 countdown;
//        BALL_DATA my_ball_data[4];
//    } COURSE_DATA;
//    my_course_data->serve_kind = serve_kind_select->currentIndex();
//    my_course_data->serve_degree = le_serve_degree->text().toUInt();
//    my_course_data->serve_sort = serve_sort_select->currentIndex();
//    my_course_data->between_group_time = le_group_gap->text().toFloat();
//    my_course_data->countdown = le_countdown->text().toUInt();


////    typedef struct Ball_Data {
////        int up_vel;              //上轮速度
////        int down_vel;            //下轮速度
////        float pitch_angle;         //俯仰角度
////        float yaw_angle;           //左右角度
////        float frequency_serve;     //频率
////        quint32 Repetitions;        //重复次数
////    } BALL_DATA;
    my_course_data->my_ball_data[0].up_vel = le_up_motor_speed->text().toInt();
    my_course_data->my_ball_data[0].down_vel = le_down_motor_speed->text().toInt();
    my_course_data->my_ball_data[0].pitch_angle = le_pitch_angle->text().toFloat();
    my_course_data->my_ball_data[0].yaw_angle = le_yaw_angle->text().toFloat();
    my_course_data->my_ball_data[0].Repetitions = le_repetition->text().toUInt();
    my_course_data->my_ball_data[0].frequency_serve = le_frequency->text().toFloat();

    QByteArray TEST("TEST!!!");
    qDebug() << TEST.data();
    QByteArray arr1 ;
    arr1.resize(4);
    memcpy(arr1.data(),&my_course_data->my_ball_data[0].up_vel,4);
    qDebug() << "arr1size:" << arr1.size();
    qDebug() << "arr1" << arr1;
    //    TEST.append()
}

void Widget::time_udp_broadcast_out()
{
//    qDebug() << "fuck";
//    *current_time = QDateTime::currentDateTime();
    //    log->append("当前时间"+(*current_time).toString("yyyy-MM-dd HH:mm:ss.zzz"));
}

void Widget::outputIp(uint8_t *ipaddress)
{
    QString str1="0";QString str2="0";
    QString str3="0";QString str4="0";
    str1 = QString::number(ipaddress[0]);
    str2 = QString::number(ipaddress[1]);
    str3 = QString::number(ipaddress[2]);
    str4 = QString::number(ipaddress[3]);
//    qDebug() << str1;

    lb_device_list->setText("设备1 ip地址:" + str1 + "." + str2 + "." + str3 + "." + str4 + "\n" + "设备1 端口号:8080");
}

